var FormAccount = function () {
	return {
		validate: function(form){
			$(form).validate(
				{
					errorElement: 'span', //default input error message container
					errorClass: 'help-inline', // default input error message class
					focusInvalid: false, // do not focus the last invalid input
					ignore: "",
					highlight: function (element) { // hightlight error inputs
						$(element)
							.closest('.help-inline').removeClass('ok'); // display OK icon
						$(element)
							.closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
					},

					unhighlight: function (element) { // revert the change dony by hightlight
						$(element)
							.closest('.control-group').removeClass('error'); // set error class to the control group
					},

					success: function (label) {
						label
							.addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
						.closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
					}
				}
			);
		},
		
		sendData: function(form){
			$.ajax({
				url: $(form).attr("action"),
				data : $(form).serialize(),
				beforeSend: function(){
					var el = jQuery("body");
					App.blockUI(el);
				},
				success: function(respon) {
				
					var el = jQuery("body");
					App.unblockUI(el);
					
					try {
						var obj = jQuery.parseJSON(respon);
						
						if(obj.status == "success"){
							$.gritter.add({
								title: 'Success',
								text: obj.msg
							});
						}else if(obj.status == "error"){
							var type = typeof obj.msg;
							if (type == "object"){
								$.each(obj.msg, function(i, dt) {
									$("#"+dt.id)
										.closest('.help-inline').removeClass('ok');
									$("#"+dt.id)
										.closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
									$("#"+dt.id).parent().children(".help-inline").text(dt.text);
								})
							}else if (type == "string"){
								$.gritter.add({
									title: 'Error',
									text: obj.msg
								});
							}
						}
						
						return false;
					} catch (e) {
						// error
						$.gritter.add({
							title: 'Error',
							text: e
						});
						return false;
					}
				},
				type: "post",
				dataType: "html"
			});
		},
		
		ajaxSubmit: function(form){
			$(form).submit(function(){
				if($(this).valid()){
					FormAccount.sendData(this);
				}
				return false;
			})
		},
		//main function to initiate the module
		init: function () {
			FormAccount.validate("#form-account");
			FormAccount.ajaxSubmit("#form-account");
			
			FormAccount.validate("#form-password");
			FormAccount.ajaxSubmit("#form-password");
		}
	}
}();

$(document).ready(function(){
	FormAccount.init();
})